/*
----------------------------------------------------------------------------
Copyright (c) 2005 - 2008, Wangxing SHI	<swxlion@gmail.com>

All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

* Redistributions of source code must retain the above
copyright notice, this list of conditions and the
following disclaimer.

* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials
provided with the distribution.

* Neither the copyright holder's name nor the names of its
contributors may be used to endorse or promote products
derived from this software without specific prior written
permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
----------------------------------------------------------------------------
*/

/*------------------------------ TMaxHeap.h -------------------------------*/
/*===========================================================================
FILE: TMaxHeap.h
Author: Wangxing SHI (swxlion)
Version: 0.0.2 
Date: 2008-12-21

File Description:
    C++ template for the Maximum Heap.
    This version using iteration rather than recursion achieve.

Require:
    Overload the "<", ">", "==", "=" four operators for type.

Dependencies:
    Platform: Platform Independent.

NOTE:
	If using with the Memory Pool, please DO NOT use the fuanction Clear(),
	Remove( , true), Delete(). And before destroy instance the heap, please ensure
	the heap is empty, because the instance will call the Clear() function in
	the destructor.

History:
version        author        date       description
----------------------------------------------------
0.0.1          swxlion       08-04-26   Created the first version. 
0.0.2          swxlion       08-12-21   Fix children count calculate error.
===========================================================================*/
#ifndef _APPLICATION_SERVER_DEVELOPMENT_LIBRARY__TMAX_HEAP_H_
#define _APPLICATION_SERVER_DEVELOPMENT_LIBRARY__TMAX_HEAP_H_

/*===============================================================================
CLASS & STRUCTURE DEFINITIONS
=============================================================================== */
namespace ASDL
{
	template <typename Type>
	class TMaxHeap
	{
	public:
		struct HeapNode
		{
			Type				Data;
			HeapNode			*Left;
			HeapNode			*Right;
			HeapNode			*Parent;
			unsigned long		LeftSize;
			unsigned long		RightSize;

			HeapNode(): Left(0), Right(0), Parent(0), LeftSize(0), RightSize(0)
			{
			}
			HeapNode( const Type &d ): Data(d), Left(0), Right(0), Parent(0), LeftSize(0), RightSize(0)
			{
			}
		};

	protected:
		HeapNode		*pRoot;

		void			Replace( HeapNode * pTree, HeapNode * pNode );
		void			ReviseSize( HeapNode * pNode, bool bInc );

		void			RotateLeft( HeapNode * pTree, HeapNode * &pNewTree );
		void			RotateRight( HeapNode * pTree, HeapNode * &pNewTree );
		
		void			MaintainUp( HeapNode * pNode );
		void			MaintainDown( HeapNode * pNode );

	public:
		TMaxHeap(): pRoot(0)
		{
		}
		~TMaxHeap()
		{
			Clear();
		}

		void		Maintain( HeapNode * pNode );
		int			Insert( HeapNode * pNode, bool bReplace = true );
		void		Remove( HeapNode * &pNode, bool bDelete = false );
		void		Clear();

		HeapNode *	FindMax()
		{
			return pRoot;
		}

		HeapNode *	Pop()
		{
			HeapNode	*pReturn = pRoot;
			Remove( pReturn, false );
			return pReturn;
		}

		void		Delete( HeapNode * &pNode )
		{
			Remove( pNode, true );
		}

	};

	template <typename Type>
	void TMaxHeap<Type>::Replace( HeapNode * pTree, HeapNode * pNode )
	{
		pNode->Left = pTree;
		pNode->LeftSize = pTree->LeftSize + pTree->RightSize + 1;

		if( pTree->Parent )
		{
			if( pTree->Parent->Left == pTree )
				pTree->Parent->Left = pNode;
			else
				pTree->Parent->Right = pNode;

			pNode->Parent = pTree->Parent;
		}
		else
			pRoot = pNode;
		
		pTree->Parent = pNode;
		ReviseSize( pNode, true );
	}

	template <typename Type>
	void TMaxHeap<Type>::ReviseSize( HeapNode * pNode, bool bInc )
	{
		while( pNode && pNode->Parent )
		{
			if( pNode->Parent->Left == pNode )
				pNode->Parent->LeftSize = bInc ? (pNode->Parent->LeftSize + 1) : (pNode->Parent->LeftSize - 1);
			else
				pNode->Parent->RightSize = bInc ? (pNode->Parent->RightSize + 1) : (pNode->Parent->RightSize - 1);

			pNode = pNode->Parent;
		}
	}

	template <typename Type>
	void TMaxHeap<Type>::RotateLeft( HeapNode * pTree, HeapNode * &pNewTree )
	{
		pNewTree = pTree->Right;
		pNewTree->Parent = pTree->Parent;
		pTree->Right = pNewTree->Left;
		if( pNewTree->Left )
			pNewTree->Left->Parent = pTree;
		pNewTree->Left = pTree;
		pTree->Parent = pNewTree;

		pTree->RightSize ^= pNewTree->LeftSize;
		pNewTree->LeftSize ^= pTree->RightSize;
		pTree->RightSize ^= pNewTree->LeftSize;

		pNewTree->LeftSize = pTree->LeftSize + pTree->RightSize + 1;
	}

	template <typename Type>
	void TMaxHeap<Type>::RotateRight( HeapNode * pTree, HeapNode * &pNewTree )
	{
		pNewTree = pTree->Left;
		pNewTree->Parent = pTree->Parent;
		pTree->Left = pNewTree->Right;
		if( pNewTree->Right )
			pNewTree->Right->Parent = pTree;
		pNewTree->Right = pTree;
		pTree->Parent = pNewTree;

		pTree->LeftSize ^= pNewTree->RightSize;
		pNewTree->RightSize ^= pTree->LeftSize;
		pTree->LeftSize ^= pNewTree->RightSize;

		pNewTree->RightSize = pTree->LeftSize + pTree->RightSize + 1;
	}

	template <typename Type>
	inline void TMaxHeap<Type>::Maintain( HeapNode * pNode )
	{
		if( pNode == NULL )
			return;

		if( pNode->Parent )
		{
			if( pNode->Data > pNode->Parent->Data )
				return MaintainUp( pNode );
		}

		return MaintainDown( pNode );
	}

	template <typename Type>
	void TMaxHeap<Type>::MaintainUp( HeapNode * pNode )
	{
		HeapNode		*pParent = pNode->Parent;

		while( pParent->Parent )
		{
			if( pNode == pParent->Left )
			{
				if( pParent == pParent->Parent->Left )
					RotateRight( pParent, pParent->Parent->Left );
				else
					RotateRight( pParent, pParent->Parent->Right );
			}
			else
			{
				if( pParent == pParent->Parent->Left )
					RotateLeft( pParent, pParent->Parent->Left );
				else
					RotateLeft( pParent, pParent->Parent->Right );
			}

			pParent = pNode->Parent;

			if( pNode->Data < pParent->Data )
				return;
		}

		if( pNode == pNode->Parent->Left )
			RotateRight( pNode->Parent, pRoot );
		else
			RotateLeft( pNode->Parent, pRoot );
	}

	template <typename Type>
	void TMaxHeap<Type>::MaintainDown( HeapNode * pNode )
	{
		bool	bLeft;
		bool	bRight;

		if( pNode->Parent == NULL )			//-- This happen just only once, don't place these sentences in cycle.
		{
			if( pNode->Left )
				bLeft  = pNode->Data < pNode->Left->Data;
			else
				bLeft = false;

			if( pNode->Right )
				bRight = pNode->Data < pNode->Right->Data;
			else
				bRight = false;

			if( bLeft && bRight )
			{
				if( pNode->Left->Data > pNode->Right->Data )
					bRight = false;
				else
					bLeft = false;
			}

			if( bLeft )
				RotateRight( pNode, pRoot );
			else if( bRight )
				RotateLeft( pNode, pRoot );
			else
				return;
		}

		while(true)
		{
			if( pNode->Left )
				bLeft  = pNode->Data < pNode->Left->Data;
			else
				bLeft = false;

			if( pNode->Right )
				bRight = pNode->Data < pNode->Right->Data;
			else
				bRight = false;

			if( bLeft && bRight )
			{
				if( pNode->Left->Data > pNode->Right->Data )
					bRight = false;
				else
					bLeft = false;
			}

			if( bLeft )
			{
				if( pNode == pNode->Parent->Left )
					RotateRight( pNode, pNode->Parent->Left );
				else
					RotateRight( pNode, pNode->Parent->Right );
			}
			else if( bRight )
			{
				if( pNode == pNode->Parent->Left )
					RotateLeft( pNode, pNode->Parent->Left );
				else
					RotateLeft( pNode, pNode->Parent->Right );
			}
			else
				return;
		}
	}

	template <typename Type>
	int TMaxHeap<Type>::Insert( HeapNode * pNode, bool bReplace )
	{
		if( !pNode )
			return 0;

		pNode->Left = NULL;
		pNode->Right = NULL;
		pNode->Parent = NULL;
		pNode->LeftSize = 0;
		pNode->RightSize = 0;

		if( !pRoot )
		{
			pRoot = pNode;
			return 0;
		}

		register HeapNode *		pCurrentNode = pRoot;
		register HeapNode *		pParentNode = NULL;

		while( pCurrentNode )
		{
			if( pCurrentNode->Data < pNode->Data )
			{
				Replace( pCurrentNode, pNode );
				return 0;
			}
			else if( pCurrentNode->Data > pNode->Data )
			{
				pParentNode = pCurrentNode;
				if( pCurrentNode->LeftSize < pCurrentNode->RightSize )
					pCurrentNode = pCurrentNode->Right;
				else
					pCurrentNode = pCurrentNode->Left;
			}
			else
			{
				if( bReplace )
					pCurrentNode->Data = pNode->Data;
				return 1;
			}
		}

		if( pParentNode->LeftSize < pParentNode->RightSize )
			pParentNode->Right = pNode;
		else
			pParentNode->Left = pNode;

		pNode->Parent = pParentNode;
		ReviseSize( pNode, true );

		return 0;
	}

	template <typename Type>
	void TMaxHeap<Type>::Remove( HeapNode * &pNode, bool bDelete )
	{
		if( !pNode )
			return;

		if( pNode->Parent == NULL )			//-- This happen just only once, don't place these sentences in cycle.
		{
			if( pNode->Left && pNode->Right )
			{
				if( pNode->Left->Data > pNode->Right->Data )
					RotateRight( pNode, pRoot );
				else
					RotateLeft( pNode, pRoot );
			}
			else
			{
				pRoot = pNode->Left ? pNode->Left : pNode->Right;
				if( pRoot )
					pRoot->Parent = NULL;

				if( bDelete )
				{
					delete pNode;
					pNode = NULL;
				}

				return;
			}
		}

		while(true)
		{
			if( pNode->Left && pNode->Right )
			{
				if( pNode->Left->Data > pNode->Right->Data )
				{
					if( pNode == pNode->Parent->Left )
						RotateRight( pNode, pNode->Parent->Left );
					else
						RotateRight( pNode, pNode->Parent->Right );
				}
				else
				{
					if( pNode == pNode->Parent->Left )
						RotateLeft( pNode, pNode->Parent->Left );
					else
						RotateLeft( pNode, pNode->Parent->Right );
				}
			}
			else
			{
				ReviseSize( pNode, false );

				if( pNode == pNode->Parent->Left )
				{
					pNode->Parent->Left = pNode->Left ? pNode->Left : pNode->Right;
					if( pNode->Parent->Left )
						pNode->Parent->Left->Parent = pNode->Parent;
				}
				else
				{
					pNode->Parent->Right = pNode->Left ? pNode->Left : pNode->Right;
					if( pNode->Parent->Right )
						pNode->Parent->Right->Parent = pNode->Parent;
				}

				if( bDelete )
				{
					delete pNode;
					pNode = NULL;
				}

				return;
			}
		}
	}

	template <typename Type>
	void TMaxHeap<Type>::Clear()
	{
		//-- Too slowly.
		//while( pRoot )
		//	Remove( pRoot, true );

		if( !pRoot )
			return;

		HeapNode		*lpFindNode = pRoot;
		HeapNode		*lpDeleteNode = NULL;

		while( lpFindNode )
		{
			if( lpFindNode->Left )
				lpFindNode = lpFindNode->Left;
			else if( lpFindNode->Right )
				lpFindNode = lpFindNode->Right;
			else
			{
				lpDeleteNode = lpFindNode;
				lpFindNode = lpFindNode->Parent;

				if( lpDeleteNode->Parent ) //-- Now, lpDeleteNode->Parent is lpFindNode. Just for eliminating data dependence.
				{
					if( lpFindNode->Left == lpDeleteNode )
						lpFindNode->Left = NULL;
					else if( lpFindNode->Right == lpDeleteNode )
						lpFindNode->Right = NULL;
				}

				delete lpDeleteNode;
			}
		}
		pRoot = NULL;
	}
}

#endif // _APPLICATION_SERVER_DEVELOPMENT_LIBRARY__TMAX_HEAP_H_
